#include "stegano.h"
#include "wav_to_text.h"

static char	*file_to_string(char	*file)
{
  FILE *ftext;
  unsigned char *temp = NULL;
  int i = 0;

  ftext = fopen(file, "r");
  temp = calloc(1, 200 * sizeof (char));

  while (!(feof(ftext)))
  {
    fread(temp + i, sizeof (char), 1, ftext);
    ++i;
  }

  fclose(ftext);
  return ((char *)(temp));
}

static void	string_to_file(char *message, char *file)
{
  FILE *ftext;
  int i = 0;

  ftext = fopen(file, "w+");

  while (message[i] != '\0')
  {
    fwrite(&message[i], sizeof (char), 1, ftext);
    ++i;
  }
  fwrite(&message[i], sizeof (char), 1, ftext);

  fclose(ftext);
}

static char    *crypto()
{
  char	*temp = NULL;
  value		*f;

  f = caml_named_value("crypt_rsa");

  String_val(caml_callback(*caml_named_value("crypt_rsa"),caml_copy_string("text")));
  temp = file_to_string("text_crypt.txt");
  return (temp);
}

static char    *decrypto(char *message)
{
  char	*temp = NULL;
  value		*f;

  f = caml_named_value("decrypt_rsa");

  String_val(caml_callback(*caml_named_value("decrypt_rsa"),caml_copy_string(message)));
  temp = file_to_string("text_decrypt.txt");
  return (temp);
}

int	stegano(char *message)
{
  int res = 1;

  string_to_file(message, "text");
  res =  text("temp.wav");
  if (res > 0)
  {
    change("temp.wav", crypto());
    system("cat header.txt binary.txt > res.wav");
    system("rm -f header.txt");
    system("rm -f binary.txt");
    system("rm -f text*");
    system("rm -f cle_*");
  }
  else
    if (res != -1)
    {
      system("rm -f header.txt");
      system("rm -f binary.txt");
    }
  system("rm -f temp.wav");
  return (res);
}

int	destegano()
{
  int res = 1;

  res =  text("temp.wav");
  if (res > 0)
  {
    answer("temp.wav");
    string_to_file(decrypto("result.txt"), "text_decrypt.txt");
    system("rm -f header.txt");
    system("rm -f binary.txt");
    system("rm -f cle_*");
    system("rm -f result.txt");
  }
  else
    if (res != -1)
    {
      system("rm -f header.txt");
      system("rm -f binary.txt");
    }
  system("rm -f temp.wav");
 return (res);
}
